package com.shop.rabbit.rabbitmq.product;

import cn.common.constant.RabbitConstants;
import cn.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Slf4j
@Component
public class TradProducer {
    @Autowired
    public RabbitTemplate rabbitTemplate;
    TradProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        initCallbacks();
    }

    private void initCallbacks() {
        rabbitTemplate.setConfirmCallback((correlation,  ack, cause)->{
            if (correlation != null) {
                log.info("Correlation  ID: {}", correlation.getId());
                if (!ack) {
                    log.error("TradProducer 消息未到达Exchange: {}", cause);
                }
            }
        });
        // 路由到Queue失败回调（需配置mandatory=true）
        rabbitTemplate.setReturnsCallback(returned  -> {
            log.error("TradProducer 消息路由失败: {}", returned.getMessage());
            log.error("TradProducer Exchange:  {}, RoutingKey: {}", returned.getExchange(),  returned.getRoutingKey());
        });
    }

    public void putEntrustBalance(String content){
        try {
            CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
            rabbitTemplate.convertAndSend(RabbitConstants.ENTRUST_BALANCE_PUT,RabbitConstants.ENTRUST_BALANCE_ROUTINGKEY_PUT,content,correlationId);
        } catch (RuntimeException e) {
            log.error("putEntrustBalance 消息发送异常", e);
            throw new BusinessException( "putEntrustBalance 消息发送失败");
        }

    }
}
